/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.bm.main.threading;

import com.bm.setting.ServerConfig;
import com.bm.util.MessagePrinter;
import com.bm.util.Util;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author ssm
 */
public class QueueFlagMessageOutbox implements Runnable {

    private int maksimum_data_per_request;
    private String url;

    public QueueFlagMessageOutbox(int maksimum_data_per_request, String url) {
        this.maksimum_data_per_request = maksimum_data_per_request;
        this.url = url;
    }

    @Override
    public void run() {
        while (true) {
            Connection conn = ServerConfig.getConnection();
            PreparedStatement pst1 = null;
            ResultSet rs = null;
            try {
                int waiting_interval = 15;

                String query = "select * from kamisa.queue_flag_message_outbox order by id_queue limit " + maksimum_data_per_request;
                pst1 = conn.prepareStatement(query);
                rs = pst1.executeQuery();

                JsonArray jsaResp = new JsonArray();
                JsonParser jse = new JsonParser();

                int queue_count = 0;
                while (rs.next()) {

                    JsonObject jsoResp = new JsonObject();
                    jsoResp.add("id_queue", jse.parse(rs.getString("id_queue")));
                    jsoResp.add("id_request", jse.parse(rs.getString("id_request")));
                    jsoResp.add("receiver", jse.parse(rs.getString("receiver")));
                    jsoResp.add("status", jse.parse(rs.getString("status")));

                    jsaResp.add(jsoResp);
                    queue_count++;
                }

                if (queue_count > 0) {
                    String data = Util.doRequestWithTimeout(jsaResp.toString(), url + "/flag_queue_message_outbox", true, 30000, 1);

                    if (data.trim().equalsIgnoreCase("none")) {
                        MessagePrinter.print("Tidak ada transaksi");
                    } else {
                        JsonArray jsa = null;
                        try {
                            jsa = jse.parse(data).getAsJsonArray();
                        } catch (Exception e) {
                            System.out.println("Error Parsing web " + e.getMessage());
                            try {
                                Thread.sleep(15 * 1000);
                            } catch (InterruptedException ex) {                                
                            }
                            ServerConfig.close(rs);
                            ServerConfig.close(pst1);
                            ServerConfig.close(conn);
                            continue;
                        }

                        for (int i = 0; i < jsa.size(); i++) {
                            waiting_interval--;
                            long id_queue = jsa.get(i).getAsLong();
                            MessagePrinter.print("Memproses " + (i + 1) + " dari " + jsa.size() + " data queue flag (id_queue : " + id_queue + ")");

                            PreparedStatement pst = null;
                            try {
                                query = "DELETE FROM kamisa.queue_flag_message_outbox where id_queue = ?";
                                pst = conn.prepareStatement(query);
                                pst.setLong(1, id_queue);
                                pst.executeUpdate();
                            } catch (SQLException ex) {
                                Logger.getLogger(QueueFlagMessageOutbox.class.getName()).log(Level.SEVERE, null, ex);
                            } finally {
                                ServerConfig.close(pst);
                            }
                        }
                    }
                }
                try {
                    if (waiting_interval <= 0) {
                        continue;
                    }
                    MessagePrinter.print("Menunggu proses outbox berikutnya selama " + waiting_interval + " detik");
                    Thread.sleep(waiting_interval * 1000);
                } catch (InterruptedException ex) {
                    ServerConfig.close(rs);
                    ServerConfig.close(pst1);
                    ServerConfig.close(conn);
                }
            } catch (SQLException ex) {
                Logger.getLogger(QueueFlagMessageOutbox.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                ServerConfig.close(rs);
                ServerConfig.close(pst1);
                ServerConfig.close(conn);
            }
        }
    }
}
